<script setup>
import { Plus, Search } from '@element-plus/icons-vue'
import {
  deleteParticipantByIdApi,
  deleteTaskByIdApi,
  getAllGroupApi,
  getAllTaskByGroupIdApi,
  getTaskByGroupIdAndNameApi,
  getUserInfoByNameApi,
  postParticipantApi,
  postTaskApi,
  putTaskApi
} from '@/apis/taskManagement'
import { onMounted, reactive, ref } from 'vue'
import { onBeforeRouteUpdate } from 'vue-router'
import { getCurrentRouteQuery } from '@/utils/routerUtils'
import { ElMessage } from 'element-plus'
import router from '@/router'

const pageParam = ref({
  pageNum: 1,
  pageSize: 10,
  total: 10
})
const taskTableLoading = ref(false)
const taskTableData = ref([])
const breadcrumb = ref()
const groups = ref([])
const taskName = ref('')
const taskDialogVisible = ref(false)
const taskDialogTitle = ref('新增任务')
const taskForm = reactive({
  data: {
    name: '', // 任务名
    description: '', // 任务描述
    groupId: '', // 工作组ID
    processRate: '0%', // 任务进度
    startTime: '', // 开始时间
    endTime: '', // 预计结束时间
    status: 0 // 任务状态
  }
})
const taskFormRules = ref({
  name: [{required: true, message: '请输入任务名', trigger: 'blur'}],
  groupId: [{required: true, message: '请选择工作组', trigger: 'blur'}],
  startTime: [{required: true, message: '请选择开始时间', trigger: 'blur'}],
  endTime: [{required: true, message: '请选择预计结束时间', trigger: 'blur'}]
})
const taskFormRef = ref()
const processRate = ['10%', '20%', '30%', '40%', '50%', '60%', '70%', '80%', '90%', '100%']
const participantDialogVisible = ref(false)
const participantForm = reactive({
  data: {
    roleDescription: '', // 任务角色描述
    roleName: '', // 任务角色
    score: 0, // 个人评分
    taskId: 0, // 任务ID
    userId: '' // 参与者ID
  }
})
const participantFormRef = ref()
const participantInfo = ref([])
const deleteParticipantVisible = ref(false)
const userIdSearchLoading = ref(false)

const getAllTaskByGroupId = groupId => {
  taskTableLoading.value = true
  getAllTaskByGroupIdApi(groupId, pageParam.value)
      .then(({data}) => {
        taskTableData.value = data.dataList
        pageParam.value.total = data.total
      })
      .finally(() => (taskTableLoading.value = false))
}

const getTaskByGroupIdAndName = (groupId, name) => {
  taskTableLoading.value = true
  getTaskByGroupIdAndNameApi(groupId, name, pageParam.value)
      .then(({data}) => {
        taskTableData.value = data.dataList
        pageParam.value.total = data.total
      })
      .finally(() => (taskTableLoading.value = false))
}

const handleSearchTaskByName = () => {
  getTaskByGroupIdAndName(getCurrentRouteQuery().groupId, taskName.value)
}

const handleDeleteParticipatant = data => {
  deleteParticipantByIdApi(data).then(() => {
    ElMessage({type: 'success', message: `删除参与者 ${ data.participantName } 成功`})
    getTaskByGroupIdAndName(getCurrentRouteQuery().groupId, taskName.value)
  })
}

const hanldeDeleteTask = task => {
  task.status = 1
  deleteTaskByIdApi(task).then(() => {
    getAllTaskByGroupId(getCurrentRouteQuery().groupId)
    ElMessage({type: 'success', message: '删除任务成功'})
  })
}

const handleSubmitTaskForm = formEl => {
  formEl.validate(valid => {
    if (valid) {
      if (taskDialogTitle.value == '新增任务') {
        postTaskApi(taskForm.data).then(() => {
          taskDialogVisible.value = false
          getAllTaskByGroupId(getCurrentRouteQuery().groupId)
          ElMessage({type: 'success', message: '新增任务成功'})
        })
      } else {
        putTaskApi(taskForm.data).then(() => {
          taskDialogVisible.value = false
          getAllTaskByGroupId(getCurrentRouteQuery().groupId)
          ElMessage({type: 'success', message: '编辑任务成功'})
        })
      }
    }
    return
  })
}

const handleCurrentChange = val => {
  pageParam.value.pageNum = val
  getTaskByGroupIdAndName(getCurrentRouteQuery().groupId, taskName.value)
}

const generateBreadcrumb = groupId => {
  breadcrumb.value = [groups.value.find(group => group.id == groupId).gName, '任务总览']
}

const searchUserIdByUserName = name => {
  getUserInfoByNameApi(name).then(({data}) => {
    participantInfo.value = data
  })
}

const handleSubmitParticipant = () => {
  postParticipantApi(participantForm.data).then(() => {
    participantDialogVisible.value = false
    getAllTaskByGroupId(getCurrentRouteQuery().groupId)
  })
}

const handleEditTask = data => {
  taskDialogVisible.value = true
  taskDialogTitle.value = '编辑任务'
  taskForm.data = data
  taskForm.data.status = taskForm.data.status == '已完结' ? 1 : 0
}

onBeforeRouteUpdate(to => {
  getAllTaskByGroupId(to.query.groupId)
  generateBreadcrumb(to.query.groupId)
})

const onGoTo = (row) => {
  router.push(`/system/projectManagement/projectTask/projectTaskDetails?taskId=${ row.id }&groupId=${ row.groupId }&name=${ row.name }`)
}

onMounted(() => {
  getAllTaskByGroupId(getCurrentRouteQuery().groupId)
  getAllGroupApi().then(({data}) => {
    groups.value = data
    breadcrumb.value = [data.find(groupId => groupId.id == getCurrentRouteQuery().groupId).gName, '任务总览']
  })
})
</script>

<template>
  <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom: 24px">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item v-for="(b, index) in breadcrumb" :key="index">{{ b }}</el-breadcrumb-item>
  </el-breadcrumb>
  <el-row :gutter="24">
    <el-col :span="4">
      <el-input v-model="taskName" placeholder="请输入任务名称进行搜索" />
    </el-col>
    <el-col :span="1.5">
      <el-button :icon="Search" type="primary" @click="handleSearchTaskByName">搜索</el-button>
    </el-col>
    <el-col :span="4">
      <el-button
          :icon="Plus"
          type="primary"
          @click=";(taskDialogVisible = !taskDialogVisible), (taskDialogTitle = '新增任务')"
      >新增任务
      </el-button
      >
    </el-col>
  </el-row>
  <el-table v-loading="taskTableLoading" :data="taskTableData" stripe style="width: 100%">
    <el-table-column prop="name" label="任务名称" width="180">
      <template #default="scope">
        <span @click="onGoTo(scope.row)" class="task-name">{{ scope.row.name }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="description" label="任务描述" width="180" />
    <el-table-column prop="creatorName" label="任务创建者" width="120" />
    <el-table-column prop="ownerName" label="负责人" width="120" />
    <el-table-column prop="status" label="任务状态" width="120" />
    <el-table-column label="当前参与人" min-width="180" width="280">
      <template #default="scope">
        <el-popover
            v-if="scope.row.participants"
            v-for="(p, index) in scope.row.participants"
            :key="index"
            placement="top-start"
            :title="'姓名：' + p.participantName"
            :width="200"
            trigger="hover"
            @hide="deleteParticipantVisible = false"
        >
          <div>角色：{{ p.roleName }}</div>
          <div>描述：{{ p.roleDescription }}</div>
          <div style="text-align: right; margin: 4px 0 0" v-if="deleteParticipantVisible">
            <el-button size="small" text @click="deleteParticipantVisible = false">取消</el-button>
            <el-button size="small" type="danger" @click="handleDeleteParticipatant(p)">确认</el-button>
          </div>
          <template #reference>
            <el-tag
                @close="deleteParticipantVisible = true"
                :closable="scope.row.operateAuth == 1"
                round
                style="margin: 0 4px"
            >
              {{ p.participantName }}
            </el-tag>
          </template>
        </el-popover>
        <span v-else-if="scope.row.operateAuth == 0"> 暂无参与人 </span>
        <el-button
            round
            v-if="scope.row.operateAuth == 1"
            :icon="Plus"
            size="small"
            @click=";(participantDialogVisible = !participantDialogVisible), (participantForm.data.taskId = scope.row.id)"
        >
          新增
        </el-button>
      </template>
    </el-table-column>
    <el-table-column prop="startTime" label="开始日期" width="180" />
    <el-table-column prop="endTime" label="结束日期" width="180" />
    <el-table-column prop="processRate" label="任务进度" width="80" />
    <el-table-column fixed="right" label="操作" width="170">
      <template #default="scope">
        <el-button round type="primary" @click="handleEditTask(scope.row)" :disabled="scope.row.operateAuth == 0">
          编辑
        </el-button>
        <el-popconfirm
            width="160"
            title="确认删除该任务？"
            confirm-button-text="确认"
            cancel-button-text="取消"
            @confirm="hanldeDeleteTask(scope.row)"
        >
          <template #reference>
            <el-button :disabled="scope.row.operateAuth == 0" round type="danger">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      background
      layout="prev, pager, next"
      :total="pageParam.total"
      :page-size="pageParam.pageSize"
      @current-change="handleCurrentChange"
  />

  <el-dialog v-model="taskDialogVisible" :title="taskDialogTitle" width="34%">
    <el-form :model="taskForm.data" ref="taskFormRef" :rules="taskFormRules" status-icon>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="taskForm.data.name" auto-complete="off" placeholder="请输入任务名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任务状态">
            <el-select v-model="taskForm.data.status" placeholder="请选择任务状态">
              <el-option label="进行中" :value="0" />
              <el-option label="已完结" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="任务描述">
            <el-input v-model="taskForm.data.description" :rows="2" type="textarea" placeholder="请输入任务描述" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
                :disabled="taskDialogTitle == '编辑任务'"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                v-model="taskForm.data.startTime"
                type="datetime"
                placeholder="开始时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预计结束时间" prop="endTime">
            <el-date-picker
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                v-model="taskForm.data.endTime"
                type="datetime"
                placeholder="预计结束时间"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="任务进度">
            <el-select v-model="taskForm.data.processRate" placeholder="请选择任务进度">
              <el-option v-for="(p, index) in processRate" :key="index" :label="p" :value="p" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作组" prop="groupId">
            <el-select v-model="taskForm.data.groupId" placeholder="请选择工作组">
              <el-option v-for="(g, index) in groups" :key="index" :label="g.gName" :value="g.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="taskDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitTaskForm(taskFormRef)">确认</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="participantDialogVisible" title="新增参与人" width="24%">
    <el-form :model="participantForm" ref="participantFormRef">
      <el-row>
        <el-col :span="24">
          <el-form-item label="参与人姓名">
            <el-select
                v-model="participantForm.data.userId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入参与人姓名"
                remote-show-suffix
                :remote-method="searchUserIdByUserName"
                :loading="userIdSearchLoading"
            >
              <el-option v-for="info in participantInfo" :key="info.id" :label="info.name" :value="info.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="参与人角色">
            <el-input
                v-model="participantForm.data.roleName"
                auto-complete="off"
                placeholder="请输入参与人角色"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="参与人描述">
            <el-input
                type="textarea"
                v-model="participantForm.data.roleDescription"
                auto-complete="off"
                placeholder="请输入参与人描述"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="participantDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitParticipant">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="less" scoped>
.el-table {
  margin-top: 24px;
}

.task-name {
  cursor: pointer;
}

.task-name:hover {
  color: #409eff;
}
</style>
